package com.ruoyi.web.admin.data;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 10100
 */
@Component
public class TcpServerInitializer extends ChannelInitializer<SocketChannel> {

    private final TcpServerHandler tcpServerHandler;

    public TcpServerInitializer(TcpServerHandler tcpServerHandler) {
        this.tcpServerHandler = tcpServerHandler;
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();

        // 拆包器：以 \r\n 为分隔符
        ByteBuf delimiter = Unpooled.copiedBuffer("#kdsjafjalsdjg#170".getBytes());
        pipeline.addLast(new DelimiterBasedFrameDecoder(2048, delimiter));

        pipeline.addLast(new StringDecoder());
        pipeline.addLast(new StringEncoder());

        // 参数含义：
        // 1. 读空闲时间（秒）：0 表示不检测读空闲
        // 2. 写空闲时间（秒）：0 表示不检测写空闲
        // 3. 读写空闲时间（秒）：60 表示在60秒内既没有读也没有写会触发超时事件
        pipeline.addLast(new IdleStateHandler(0, 0, 600, TimeUnit.SECONDS));
        pipeline.addLast(new HeartbeatHandler());

        pipeline.addLast(tcpServerHandler);
    }
}